package com.pinc.poop;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.widget.RemoteViews;

public class BroadcastService extends Service {

	private SharedPreferences settings;
	private DBClass dbHelper;
	private Handler handler= new Handler();
	private int latest_id;
	private boolean notified;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		notified = false;
		latest_id = -1;
		dbHelper = new DBClass(this);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		handleCommand();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		handleCommand();
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		handler.removeCallbacks(CheckPeriod);
		notified = false;
		latest_id = -1;
		dbHelper.close();
	}

	private final Runnable CheckPeriod = new Runnable()
	{
		public void run()
		{
			int total;
			Cursor cs = dbHelper.getRecord(null, null, "date DESC, time DESC");
			total = cs.getCount();
			if ( total > 0)
			{
				PincDate now = new PincDate();
				now.setToNow();
				settings = PreferenceManager.getDefaultSharedPreferences(BroadcastService.this);
				int period = settings.getInt("user_period_int", 48);

				if(cs.moveToFirst())
				{
					String datestr = cs.getString(cs.getColumnIndex("date"));
					String timestr = cs.getString(cs.getColumnIndex("time"));
					int tmp_id = cs.getInt(cs.getColumnIndex("_id"));
					if ( latest_id != tmp_id)
					{
						notified = false;
						latest_id = tmp_id;
					}
					if ( !notified)
					{
						String newtimestr = timestr.replace(":", "");
						String parsestr = String.format("%sT%s00", datestr, newtimestr);
						PincDate md = new PincDate();
						md.parse(parsestr);
						long mins = md.diffInMins(now);
						long hours = mins / 60;
						if ( hours >= period)
						{
							notified = true;
							ShowStatusBar("", String.format("%s %d %s", getResources().getString(R.string.str_noti_str1),period, getResources().getString(R.string.str_noti_str2)),"");
						}
					}
				}
			}
			cs.close();
			dbHelper.close();
			handler.postDelayed(this, 5*60*1000);
		}
	};

	private void ShowStatusBar(String l_title, String title, String Text)
	{
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

		int icon = R.drawable.noti_icon;
		CharSequence tickerText = l_title;
		long when = System.currentTimeMillis();

		Notification notification = new Notification(icon, tickerText, when);

		RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_noti_layout);
		contentView.setImageViewResource(R.id.image, icon);
		contentView.setTextViewText(R.id.text, title);
		notification.contentView = contentView;

		Intent notificationIntent = new Intent(this, calendar.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		if ( settings.getBoolean("user_vibra", false))
			notification.defaults |= Notification.DEFAULT_VIBRATE;

		notification.contentIntent = contentIntent;

		startForeground(0, notification);
		mNotificationManager.notify(0, notification);
	}

	public void handleCommand()
	{
		settings = PreferenceManager.getDefaultSharedPreferences(this);

		if (!settings.getBoolean("user_noti", false) )
		{
			this.stopSelf();
		}

		handler.removeCallbacks(CheckPeriod);
		handler.post(CheckPeriod);
	}

}
